<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/12
 * Time: 18:20
 * @link http://www.lmterp.cn
 */

namespace app\common\service\product;

use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\ProductAmazonBox;
use app\common\model\ProductCategory;
use app\common\model\Product;
use app\common\model\ProductPlatformBarcode;
use app\common\model\ProductPlatformSku;
use app\common\model\ProductPurchase;
use app\common\model\ProductStore;
use app\common\service\BaseService;

class PlatformService extends BaseService
{
    /**
     * 通过平台 sku 获取内部 sku, 如果有则返回内部 sku， 否则返回平台 sku
     * @param string $psku
     * @date 2020/08/12
     * @author longli
     * @return string|array
     */
    public function getSkuByPlatformSku($psku = '')
    {
        $obj = ProductPlatformSku::field(['sku'])->where("platform_sku", $psku)->select();
        if($obj->isEmpty()) return $psku;
        $skus = [];
        foreach($obj as $s)
        {
            $skus[] = trim($s->sku);
        }
        return count($skus) > 1 ? $skus : $skus[0];
    }

    /**
     * 生成平台唯一 sku
     * @param int $num 生成的数量
     * @date 2020/08/12
     * @author longli
     * @return string|string[]
     */
    public function generatePlatformSku($num = 1)
    {
        if($num < 1) return "";
        $ret = [];
        $step = $num;
        while($step--)
        {
            do
            {
                $psku = Tools::getRandStr(mt_rand(8, 10), 2);
            }while(in_array($psku, $ret) || ProductPlatformSku::hasPlatformSku($psku));
            $ret[] = $psku;
        }
        if($num == 1) return $ret[0];
        return $ret;
    }

    /**
     * 通过变体 id 生成平台SKU
     * @param int $accountId 账号id
     * @param int[] $storeIds 变体 id
     * @param bool $force 如果存在是否再次生成，默认不生成
     * @return bool
     * @date 2020/09/15
     * @author longli
     */
    public function generateSkuByStoreId($accountId, $storeIds = [], $force = false)
    {
        if(!is_array($storeIds)) $storeIds = explode(',', $storeIds);
        $pskus = $this->generatePlatformSku(count($storeIds));
        if(!is_array($pskus)) $pskus = [$pskus];
        $data = [];
        foreach(ProductStore::field("product_id,sku,store_id")->where("store_id", "in", $storeIds)->select() as $k => $item)
        {
            if(!$force && ProductPlatformSku::hasByStoreAccount($accountId, $item->store_id)) continue;
            $data[] = [
                'product_id'   => $item->product_id,
                'store_id'     => $item->store_id,
                'account_id'   => $accountId,
                "platform_sku" => $pskus[$k],
                "sku"          => $item->sku,
            ];
        }
        try
        {
            if(!empty($data)) ProductPlatformSku::insertAll($data);
            return true;
        }catch (\Exception $e)
        {
            return false;
        }
    }

    /**
     * 通过已生的平台SKU, 再次生成
     * @param array $pid
     * @return bool
     * @date 2020/09/16
     * @author longli
     */
    public function generateSkuByPid($pid = [])
    {
        if(!is_array($pid)) $pid = explode(',', $pid);
        $data = [];
        foreach(ProductPlatformSku::where("pid", "in", $pid)->select()->toArray() as $item)
        {
            $t = Tools::visibleArray(['product_id', 'store_id', 'sku', 'account_id'], $item);
            $t['platform_sku'] = $this->generatePlatformSku(1);
            $data[] = $t;
        }
        if(empty($data)) return false;
        return ProductPlatformSku::limit(500)->insertAll($data) > 0;
    }

    /**
     * 生成平台条码，暂只处理亚马逊平台
     * @param string $pathPdf 平台 pdf 地址
     * @param string $output 合成后保存地址，如果为空直接直接输出到浏览器
     * @param string $text 需要添加的文字
     * @return bool
     * @date 2021/01/16
     * @author longli
     */
    public function generatePlatformBarcode($pathPdf, $output = '', $text = '')
    {
        if(!is_file($pathPdf)) return false;
        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'UTF-8',
            'format' => [55, 30],
        ]);
        $mpdf->addPage();
        $mpdf->setSourceFile($pathPdf);
        if(!empty($text)) $mpdf->WriteText(15, 25, $text);
        $tpId = $mpdf->importPage(1);
        $mpdf->useTemplate($tpId, -13, -18);
        ob_end_clean();
        if(!empty($output))
        {
            $dir = dirname($output);
            if(!is_dir($dir)) mkdir($dir, 0777, true);
        }
        $mpdf->Output($output);
        return true;
    }

    /**
     * 根据亚马逊箱唛生成 100*100 箱唛
     * @param string $pathPdf 平台 pdf 地址
     * @param int $boxNum 总箱数，默认1箱
     * @param int $index 指定打印的页码，默认打印全部
     * @param string $output 合成后保存地址，如果为空直接直接输出到浏览器
     * @return bool|string
     * @date 2021/01/16
     * @author longli
     */
    public function amazonBox($pathPdf, $boxNum = 1, $index = 0, $output = '')
    {
        if(!is_file($pathPdf)) return false;
        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'UTF-8',
            'format' => [100, 100],
        ]);
        $split = [
            ['x' => -2, 'y' => -5],
            ['x' => -2, 'y' => -140],
            ['x' => -105, 'y' => -5],
            ['x' => -105, 'y' => -140],
        ];
        $count = $mpdf->setSourceFile($pathPdf);
        $boxTotal = 0;
        for($i = 1; $i <= $count; $i++)
        {
            for($j = 0; $j < 4; $j++)
            {
                if($boxTotal == $boxNum) break;
                $boxTotal++;
                if($index > 0 && $boxTotal != $index) continue;
                $mpdf->addPage();
                $tpId = $mpdf->importPage($i);
                $mpdf->useTemplate($tpId, $split[$j]['x'], $split[$j]['y']);
            }

        }
        ob_end_clean();
        if(!empty($output))
        {
            $dir = dirname($output);
            if(!is_dir($dir)) mkdir($dir, 0777, true);
        }
        $mpdf->Output($output);
        return $output;
    }

    /**
     * 添加平台条码信息
     * @param array $data 条码信息
     * @return ProductPlatformBarcode|bool
     * @date 2021/01/16
     * @author longli
     */
    public function addBarcode($data = [])
    {
        $bData = ProductPlatformBarcode::getFilterField($data, '');
        if(empty($bData)) return false;
        $bData = Tools::trim($bData);
        $barcode = null;
        if(isset($bData['barcode_id'])) $barcode = ProductPlatformBarcode::get($bData['barcode_id']);
        if(!empty($bData['merge_path_pdf'])) $bData['is_merge'] = ProductPlatformBarcode::IS_YES;
        if(!empty($bData['sku']) && ($store = ProductStore::getStoreBySku($bData['sku'])))
            $bData += ['name_ch' => $store->product->name_ch, 'image_url' => $store->image_url];
        if(!empty($barcode))
        {
            $barcode->save($bData);
        }
        else
        {
            $barcode = ProductPlatformBarcode::create($bData)->refresh();
        }
        return $barcode;
    }

    /**
     * 添加亚马逊箱唛
     * @param array $data 箱唛信息
     * @return ProductAmazonBox|false
     * @date 2021/04/19
     * @author longli
     */
    public function addAmazonBox($data)
    {
        $bData = ProductAmazonBox::getFilterField($data, '');
        if(empty($bData)) return false;
        $bData = Tools::trim($bData);
        $boxCode = null;
        if(isset($bData['box_id'])) $boxCode = ProductAmazonBox::get($bData['box_id']);
        if(!empty($boxCode))
        {
            $boxCode->save($bData);
        }
        else
        {
            $boxCode = ProductAmazonBox::create($bData)->refresh();
        }
        return $boxCode;
    }
}